package homework;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author mubei
 * @date 2021/11/28
 * @description
 */
public class Demo03 {

    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        for (int i = 1; i < 11; i++) {
            final int t = i;
            Producer producer = new Producer(container);
            new Thread(()->{
                try {
                    producer.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"生产者"+t).start();
        }

        for (int i = 0; i < 10; i++) {
            final int t = i;
            Customer customer = new Customer(container);
            new Thread(()->{
                try {
                    customer.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"消费者"+t).start();
        }
    }
}

class Producer {
    SynContainer container;

    static int sum = 0 ;
    public Producer(SynContainer container) {
        this.container = container;
    }


    public void run() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName()+"生产第:"+sum+"个鸡");
            container.push(new Chicken(sum));
            sum ++;
        }
    }



}

class Customer {
    SynContainer container;

    public Customer(SynContainer container) {
        this.container = container;
    }

    public void run() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            int pop = container.pop();
            System.out.println(Thread.currentThread().getName()+"消费:"+pop+"个鸡");
        }
    }


}

class Chicken {
    int id;//产品编号

    public Chicken(int id) {
        this.id = id;
    }
}

// 缓冲区
class SynContainer {
    //需要一个容器大小
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    public synchronized void push(Chicken chicken) throws InterruptedException {
        while(count == 10){
            wait(10);
        }
        chickens[count++] = chicken;
        notifyAll();
    }

    public synchronized int pop()  throws InterruptedException{
        while(count == 0){
            wait(10);
        }
        notifyAll();
        return chickens[--count].id;
    }



}

